package com.supermap.desktop.framemenus;

import java.awt.Component;
import java.io.File;
import java.text.MessageFormat;
import java.util.ArrayList;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import com.supermap.data.Datasource;
import com.supermap.data.DatasourceConnectionInfo;
import com.supermap.desktop.Application;
import com.supermap.desktop.CommonToolkit;
import com.supermap.desktop.Interface.IBaseItem;
import com.supermap.desktop.Interface.IForm;
import com.supermap.desktop.dataview.DataViewProperties;
import com.supermap.desktop.implement.CtrlAction;
import com.supermap.desktop.properties.CommonProperties;
import com.supermap.desktop.properties.CoreProperties;
import com.supermap.desktop.ui.UICommonToolkit;
import com.supermap.desktop.ui.controls.SmFileChoose;
import com.supermap.desktop.ui.controls.WorkspaceTree;

public class CtrlActionDatasourceOpenFile extends CtrlAction {

	public CtrlActionDatasourceOpenFile(IBaseItem caller, IForm formClass) {
		super(caller, formClass);
	}

	@Override
	public void run() {
		try {
			/**
			 * 需要选中的数据源名称
			 */
			if (!SmFileChoose.isModuleExist("DatasourceOpenFile")) {
				String fileFilters = SmFileChoose.createFileFilter(DataViewProperties.getString("String_FileFilters_Datasourse"), "udb");
				SmFileChoose.addNewNode(fileFilters, CommonProperties.getString("String_DefaultFilePath"),
						DataViewProperties.getString("String_Title_DatasoursesOpenFile"), "DatasourceOpenFile", "OpenMany");
			}

			SmFileChoose openFileDlg = new SmFileChoose("DatasourceOpenFile");
			Component parent = (Component) Application.getActiveApplication().getMainFrame();
			if (openFileDlg.showDefaultDialog() == JFileChooser.APPROVE_OPTION) {
				String message = "";
				int failedCount = 0;

				boolean isReadOnlyOpen = true;
				boolean isAllDatasourceExcuteThis = false;
				File[] files = openFileDlg.getSelectedFiles();
				for (int i = 0; i < files.length; i++) {
					String filePath = files[i].getPath();
					boolean isReadOnly = false;

					File uddFile = null;
					Datasource datasource = null;
					if (filePath.toLowerCase().endsWith(".udb")) {
						String uddFilePath = filePath.substring(0, filePath.lastIndexOf(".")) + ".udd";
						uddFile = new File(uddFilePath);
					}
					// TODO 文件只读时提示
					if (uddFile.exists()) {
						if (!isReadOnly && (!files[i].canWrite() || !uddFile.canWrite())) {
							if (!isAllDatasourceExcuteThis) {
								message = MessageFormat.format(CoreProperties.getString("String_OpenReadOnlyDatasourceWarning"), filePath);

								int dialogResult = UICommonToolkit.showConfirmDialog(message);
								if (dialogResult == JOptionPane.YES_OPTION) {
									isReadOnly = true;
								} else {
									isReadOnlyOpen = false;
								}
								isAllDatasourceExcuteThis = true;
							} else {
								isReadOnly = true;
							}

							if (isReadOnlyOpen) {
								datasource = CommonToolkit.DatasourceWrap.openFileDatasource(filePath, "", isReadOnly, true);
							} else {
								message = String.format(CoreProperties.getString("String_OpenDatasourceFailed"), filePath);
								Application.getActiveApplication().getOutput().output(message);
								failedCount++;
								continue;
							}
						} else {
							datasource = CommonToolkit.DatasourceWrap.openFileDatasource(filePath, "", isReadOnly, true);
							if (null != datasource) {
								// 设置数据源选中
								UICommonToolkit.refreshSelectedDatasourceNode(datasource.getAlias());
							}
						}
					}

					if (datasource == null) {
						// 如果是密码错误就提示让用户输入密码再打开一次，如果还失败则不再提示了。
						boolean isCancel = false;
						while (datasource == null && CommonToolkit.DatasourceWrap.isPasswordWrong() && !isCancel) {
							String info = String.format(CoreProperties.getString("String_InputDatasourcePassword"), files[i].getName());

							String passWord = JOptionPane.showInputDialog(parent, info, "");
							if (passWord == null) {
								isCancel = true;
							} else {
								datasource = CommonToolkit.DatasourceWrap.openFileDatasource(filePath, passWord, isReadOnly, false);
							}
						}
					}

					if (datasource == null) {
						failedCount++;
						message = String.format(CoreProperties.getString("String_OpenDatasourceFailed"), filePath);
						Application.getActiveApplication().getOutput().output(message);
					}
				}

				if (openFileDlg.getSelectedFiles().length > 1) {
					message = String.format(CoreProperties.getString("String_OpenDatasourceResultMsg"), openFileDlg.getSelectedFiles().length,
							openFileDlg.getSelectedFiles().length - failedCount, failedCount);
					Application.getActiveApplication().getOutput().output(message);
				}
			}

		} catch (Exception ex) {
			Application.getActiveApplication().getOutput().output(ex);
		}
	}

	@Override
	public boolean enable() {
		return true;
	}
}
